package com.lcxw.hxzbapi.controller.appcontroller;

import com.alibaba.fastjson.JSONObject;
import com.lcxw.hxzbapi.common.AppleUtil;
import com.lcxw.hxzbapi.controller.membercontroller.MemberRealization;
import com.lcxw.hxzbapi.entity.pojo.Photo;
import com.lcxw.hxzbapi.entity.pojo.YwpdMember;
import com.lcxw.hxzbapi.entity.response.Response;
import com.lcxw.hxzbapi.service.PhotoService;
import com.lcxw.hxzbapi.service.YwpdMemberService;
import com.lcxw.hxzbapi.tencentim.common.TencentImRealization;
import com.lcxw.hxzbcommon.common.AesCBCUtil;
import com.lcxw.hxzbcommon.common.RedisUtils;
import com.lcxw.hxzbcommon.entity.CommonBean;
import com.lcxw.hxzbcommon.entity.ErrorCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Lazy;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/user")
@CrossOrigin
@Validated
public class IosLoginController {

    private Logger logger = LoggerFactory.getLogger(IosLoginController.class);

    @Resource
    YwpdMemberService ywpdMemberService;

    @Resource
    RedisUtils redisUtils;

    @Resource
    MemberRealization memberRealization;

    @Resource
    TencentImRealization tencentImRealization;

    @Resource
    @Lazy
    PhotoService photoService;

    final String APPID = CommonBean.WECHAT_APPID;
    final String SECRET = CommonBean.WECHAT_SECRET;

    @PostMapping("/thirdParty/iosLogin")
    public Response thirdPartyLogin(@RequestBody JSONObject requestParams) throws Exception {
        String identityToken = requestParams.getString("identityToken");
        String lastLogIp = requestParams.getString("ip");
        String longitude = requestParams.getString("longitude");
        String latitude = requestParams.getString("latitude");
        logger.info("第三方登录请求：" + requestParams.toJSONString());
        if(!AppleUtil.verify(identityToken)){
            return Response.ok("授权验证失败");
        }
        //对identityToken解码
        JSONObject json = AppleUtil.parserIdentityToken(identityToken);
        if(json == null){
            return Response.ok("授权解码失败");
        }
        String iosId=json.getString("sub");
        YwpdMember ywpdMember = ywpdMemberService.selectByiosId(iosId);
        if (null != ywpdMember) {
            //判断用户是否被后台注销
            if (1 == ywpdMember.getCancelled()) {
                return Response.common(logger, "user is cancelled.", ErrorCode.LOSE_EFFICACY,
                    "user is cancelled.", null);
            }
            JSONObject data = new JSONObject();
            data.put("verifyTelephone", "false");
            data.put("telephone", ywpdMember.getTelephone());
            data.put("userId", ywpdMember.getUserId());
            //构造token 使用userId和时间戳，生成唯一token
            String tokenKey =
                ywpdMember.getUserId() + ":" + Calendar.getInstance().getTimeInMillis();
            String token = null;
            try {
                token = AesCBCUtil.getInstance().encrypt(tokenKey);
            } catch (Exception e) {
                e.printStackTrace();
                logger.error("token编码失败");
            }
            redisUtils
                .string_set("uid:" + ywpdMember.getUserId() + ":token", token, 60 * 60 * 24 * 30);

            ywpdMember.setLastLogIp(lastLogIp);
            ywpdMember.setLongitude(longitude);
            ywpdMember.setLatitude(latitude);
            try {
                ywpdMemberService.updateYwpdMember(ywpdMember);
            } catch (Exception e) {
                e.printStackTrace();
            }
            data.put("token", token);
            return Response.ok(data);
        } else {
            JSONObject data = new JSONObject();
            data.put("verifyTelephone", "true");
            data.put("iosId", iosId);
            return Response.ok(data);
        }
    }

    @PostMapping("/thirdParty/relateIosUser")
    public Response relateUser(@RequestBody JSONObject requestParams) {
        String telephone = requestParams.getString("telephone");
        String iosId = requestParams.getString("iosId");
        try{
            YwpdMember ywpdMember = ywpdMemberService.selectYwpdMemberByTelephone(telephone);
            //获取到微信平台的用户信息
            String userId = null, setPassword;
            JSONObject data = new JSONObject();
            String nickName=telephone.substring(6);
            String imgUrl="https://ywpd-picture.obs.cn-east-2.myhuaweicloud.com/photo/131770091-8_photo.png?AccessKeyId=TEPZ5RHAPORK7NWI4AI9&Expires=1697771426&Signature=OlkGszEHugy5tMi%2FcTKcPLzsri0%3D";
            if (null != ywpdMember) {
                ywpdMember.setIosId(iosId);
                ywpdMemberService.updateYwpdMember(ywpdMember);
                userId = ywpdMember.getUserId() + "";
                //告诉前端是否还需要设置密码
                setPassword = "false";
                String token = memberRealization.genToken(userId);
                data.put("userId", ywpdMember.getUserId());
                data.put("token", token);
                data.put("setPassword", setPassword);
            } else {
                //手機號碼不存在，則新建一個用戶
                YwpdMember newMember = new YwpdMember();
                newMember.setNickName(nickName);
                newMember.setIosId(iosId);
                newMember.setTelephone(telephone);
                newMember.setPassword("123456");
                Response register = ywpdMemberService.register("", newMember);
                Map registerData = (Map) register.getData();
                //告诉前端是否还需要设置密码
                setPassword = "true";
                userId = registerData.get("userId") + "";
                data.put("userId", userId);
                data.put("token", registerData.get("token"));
                //将新用户的信息同步到腾讯的IM系统
                JSONObject imBody = new JSONObject();
                imBody.put("From_Account", registerData.get("userId") + "");
                List<JSONObject> profileItem = new ArrayList<>();
                JSONObject p1_nickName = new JSONObject();
                p1_nickName.put("Tag", "Tag_Profile_IM_Nick");
                p1_nickName.put("value", nickName);
                profileItem.add(p1_nickName);
                JSONObject p2_sex = new JSONObject();
                p2_sex.put("Tag", "Tag_Profile_IM_Gender");
                String imSex = "Gender_Type_Unknown";
                p2_sex.put("value", imSex);
                profileItem.add(p2_sex);
                JSONObject p3_imgUrl = new JSONObject();
                p3_imgUrl.put("Tag", "Tag_Profile_IM_Image");
                p3_imgUrl.put("value", imgUrl);
                profileItem.add(p3_imgUrl);
                imBody.put("ProfileItem", profileItem);
                tencentImRealization.updateImUserInfo(imBody);
                Photo photo = new Photo();
                photo.setUserId(Long.valueOf(userId));
                photo.setPhotoName(userId + "-1");
                photo.setPhotoUrl(imgUrl);
                photoService.insert(photo);
                data.put("setPassword", setPassword);
            }
            return Response.ok(data);
        }catch (Exception e){
            e.printStackTrace();
        }
        return Response.ok();

    }

}
